// plugins/VersionUpdateWebpackPlugin.js
const fs = require('fs');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

class VersionUpdateWebpackPlugin {
  constructor(options = {}) {
    this.options = {
      versionFile: 'version.json',
      checkInterval: 300000, // 5分钟检查一次
      alertMessage: '发现新版本可用，请刷新页面获取最新内容。',
      autoReload: false,
      storageKey: 'app_version_info',
      ...options
    };
  }

  apply(compiler) {
    // 生成版本数据
    const versionData = {
      version: Date.now(),
      buildTime: new Date().toISOString(),
      buildDate: new Date().toLocaleString('zh-CN')
    };

    // 在emit阶段（生成资源到output目录之前）写入版本文件
    compiler.hooks.emit.tapAsync('VersionUpdateWebpackPlugin', (compilation, callback) => {
      const versionContent = JSON.stringify(versionData, null, 2);
      
      // 将版本文件添加到webpack的输出中
      compilation.assets[this.options.versionFile] = {
        source: () => versionContent,
        size: () => versionContent.length
      };

      console.log(`[VersionUpdateWebpackPlugin] 📦 版本文件已添加: v${versionData.version}`);
      callback();
    });

    // 向HTML注入版本检查代码
    if (compiler.hooks) {
      compiler.hooks.compilation.tap('VersionUpdateWebpackPlugin', (compilation) => {
        HtmlWebpackPlugin.getHooks(compilation).beforeEmit.tapAsync(
          'VersionUpdateWebpackPlugin',
          (data, cb) => {
            data.html = data.html.replace('</body>', `${this.getVersionScript()}</body>`);
            cb(null, data);
          }
        );
      });
    }
  }

  getVersionScript() {
    const {
      versionFile,
      checkInterval,
      alertMessage,
      autoReload,
      storageKey
    } = this.options;

    return `
<!-- 版本更新检查 -->
<script>
(function() {
  const STORAGE_KEY = '${storageKey}';
  let checkTimer = null;
  let isChecking = false;

  // 初始化版本检查
  function initVersionCheck() {
    const savedVersion = getSavedVersion();
    
    checkForUpdate(savedVersion).then(data => {
      if (data) {
        saveVersion(data.version);
        console.log('📦 当前版本:', data.version);
        
        startPeriodicCheck();
        document.addEventListener('visibilitychange', handleVisibilityChange);
        window.addEventListener('online', handleOnline);
      }
    }).catch(console.error);
  }

  // 从localStorage获取保存的版本
  function getSavedVersion() {
    try {
      const saved = localStorage.getItem(STORAGE_KEY);
      return saved ? JSON.parse(saved) : null;
    } catch (error) {
      console.warn('读取保存的版本信息失败:', error);
      return null;
    }
  }

  // 保存版本到localStorage
  function saveVersion(version) {
    try {
      localStorage.setItem(STORAGE_KEY, JSON.stringify({
        version: version,
        lastCheck: Date.now()
      }));
    } catch (error) {
      console.warn('保存版本信息失败:', error);
    }
  }

  // 获取最新版本信息
  async function fetchVersion() {
    try {
      const response = await fetch('./${versionFile}?t=' + Date.now(), {
        cache: 'no-cache',
        headers: {
          'Cache-Control': 'no-cache',
          'Pragma': 'no-cache'
        }
      });
      if (!response.ok) throw new Error('网络响应异常');
      return await response.json();
    } catch (error) {
      console.warn('⚠️ 获取版本信息失败:', error.message);
      return null;
    }
  }

  // 检查版本更新
  async function checkForUpdate(savedVersionInfo = null) {
    if (isChecking) return;
    isChecking = true;

    try {
      const newData = await fetchVersion();
      if (!newData) return null;

      const savedVersion = savedVersionInfo || getSavedVersion();
      const currentVersion = savedVersion ? savedVersion.version : null;

      if (currentVersion && newData.version !== currentVersion) {
        console.log('🆕 发现新版本:', newData.version, '当前版本:', currentVersion);
        showUpdateNotification(newData);
      }

      return newData;
    } catch (error) {
      console.warn('版本检查失败:', error.message);
      return null;
    } finally {
      isChecking = false;
    }
  }

  // 显示更新通知
  function showUpdateNotification(versionData) {
    const existingNotice = document.getElementById('version-update-notice');
    if (existingNotice) existingNotice.remove();

    const notice = document.createElement('div');
    notice.id = 'version-update-notice';
    notice.style = \`
      position: fixed;
      top: 20px;
      right: 20px;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      padding: 16px 20px;
      border-radius: 8px;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
      z-index: 10000;
      max-width: 320px;
      font-family: -apple-system, BlinkMacSystemFont, sans-serif;
    \`;

    notice.innerHTML = \`
      <div style="display: flex; align-items: center; margin-bottom: 8px;">
        <span style="font-size: 18px; margin-right: 8px;">🔄</span>
        <strong style="font-size: 14px;">发现新版本</strong>
      </div>
      <div style="font-size: 12px; opacity: 0.9; margin-bottom: 8px;">
        ${alertMessage}
      </div>
      <div style="font-size: 11px; opacity: 0.7; margin-bottom: 12px;">
        构建时间: \${new Date(versionData.buildTime).toLocaleString('zh-CN')}
      </div>
      <div style="display: flex; gap: 8px;">
        <button onclick="handleUpdateAction()" style="
          background: rgba(255, 255, 255, 0.2);
          border: 1px solid rgba(255, 255, 255, 0.3);
          color: white;
          padding: 8px 16px;
          border-radius: 4px;
          cursor: pointer;
          font-size: 12px;
          flex: 1;
        ">立即刷新</button>
        <button onclick="this.parentElement.parentElement.remove()" style="
          background: transparent;
          border: 1px solid rgba(255, 255, 255, 0.3);
          color: white;
          padding: 8px 12px;
          border-radius: 4px;
          cursor: pointer;
          font-size: 12px;
        ">稍后</button>
      </div>
    \`;

    document.body.appendChild(notice);

    setTimeout(() => {
      if (notice.parentElement) notice.remove();
    }, 30000);
  }

  // 处理更新操作
  window.handleUpdateAction = function() {
    if (${autoReload}) {
      window.location.reload();
    } else {
      if (confirm('确定要刷新页面获取最新版本吗？')) {
        window.location.reload();
      }
    }
  }

  // 开始定期检查
  function startPeriodicCheck() {
    if (checkTimer) clearInterval(checkTimer);
    checkTimer = setInterval(() => checkForUpdate(), ${checkInterval});
  }

  // 页面可见性变化处理
  function handleVisibilityChange() {
    if (!document.hidden) checkForUpdate();
  }

  // 网络恢复时检查
  function handleOnline() {
    checkForUpdate();
  }

  // 页面加载完成后初始化
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initVersionCheck);
  } else {
    initVersionCheck();
  }

  window.checkVersionUpdate = () => checkForUpdate();
})();
</script>
`;
  }
}

module.exports = VersionUpdateWebpackPlugin;